package com.ls.herostory.cmdhandler;

import com.ls.herostory.login.UserManager;
import com.ls.herostory.msg.GameMsgProtocol;
import com.ls.herostory.session.Session;
import com.ls.herostory.session.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/14 9:14
 * @since
 */
public class SelectHeroCmdHandler implements CmdHandler<GameMsgProtocol.SelectHeroCmd> {

    @Override
    public void handleCmd(ChannelHandlerContext ctx, GameMsgProtocol.SelectHeroCmd cmd) {
        Session session = SessionUtil.getSession((NioSocketChannel) ctx.channel());

        if(session == null){
            GameMsgProtocol.SelectHeroResult.Builder builder = GameMsgProtocol.SelectHeroResult.newBuilder();
            builder.setHeroAvatar(""); // 失败
            GameMsgProtocol.SelectHeroResult selectHeroResult = builder.build();
            ctx.writeAndFlush(selectHeroResult);

        }else{
            UserManager.getInstance().asyncUpdateHero(session.getUserId(), cmd.getHeroAvatar(), (success)->{
                GameMsgProtocol.SelectHeroResult.Builder builder = GameMsgProtocol.SelectHeroResult.newBuilder();
                if(success){
                    // 更新session
                    session.setHeroAvatar(cmd.getHeroAvatar());
                    //
                    builder.setHeroAvatar(session.getHeroAvatar());
                }else{
                    builder.setHeroAvatar(""); // 失败
                }
                // 返回消息
                GameMsgProtocol.SelectHeroResult selectHeroResult = builder.build();
                ctx.writeAndFlush(selectHeroResult);
            });
        }

    }

}
